//
//  QSViewController.m
//  ThreeFolks
//
//  Created by Pibinuo on 15/11/27.
//  Copyright © 2015年 皮比诺. All rights reserved.
//

#import "QSViewController.h"
#import "AppDelegate.h"
#import "TypePlainTableViewCell.h"
#import "TypePictureTableViewCell.h"
#import "PickButton.h"
#import "AFHTTPSessionManager.h"
#import "DataModel.h"
#import "UIImageView+WebCache.h"
#import "UMSocial.h"
#import "MJRefresh.h"
#import "LocalNew/Controller/Header.h"
#import "SoundHelper.h"

@interface QSViewController ()<UITableViewDelegate,UITableViewDataSource,UMSocialUIDelegate,CLLocationManagerDelegate,localControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)PickButton * sixButton;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,strong)NSIndexPath * indexPath;
@property(nonatomic,assign)NSInteger ButtonIndex;

#pragma mark ---- 第二页面
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, assign) CGFloat height;
//定位
@property (nonatomic, strong) CLLocationManager * manager;
@property (nonatomic, strong) CLGeocoder * georoder;
@property (nonatomic, strong) NSString * province;//省
@property (nonatomic, strong) NSString * city;//市
@property (nonatomic, strong) NSString * district;//区
@property (nonatomic, strong) NSString * choicetype;
@property (nonatomic, strong) NSString * choicename;
@property (nonatomic, strong) Modefy * classify;

@end

@implementation QSViewController
static int count = 1;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.leftSlider setPanEnabled:YES];
    

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self AboutDrawer];
    self.ButtonIndex = 0;
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];

    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"head_background"] forBarMetrics:(UIBarMetricsDefault)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    self.sixButton = [[PickButton alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    
    __block typeof(self) pSelf = self;
    self.sixButton.myBlock = ^(NSInteger index){
        pSelf.ButtonIndex = index;
        [pSelf.tableView reloadData];
    };
    
    [self.view addSubview:self.sixButton];
    
    [self makedata];
    self.dataArray = [NSMutableArray array];
    
#pragma mark ===== 第二页面
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位未打开，请设置打开");
        return;
    }
    [self.manager requestAlwaysAuthorization];
    self.manager.delegate = self;
    [self.manager startUpdatingLocation];
    self.manager.desiredAccuracy = kCLLocationAccuracyBest;
    if (self.city == nil) {
        self.navigationItem.title = [NSString stringWithFormat:@"正在定位"];
    } else {
        self.navigationItem.title = [NSString stringWithFormat:@"当前的城市是：%@",self.city];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //注册
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[NewsOneTableViewCell class] forCellReuseIdentifier:@"cell_one"];
    [self.tableView registerClass:[NewsTwoTableViewCell class] forCellReuseIdentifier:@"cell_two"];
    [self.tableView registerClass:[Topic2TableViewCell class] forCellReuseIdentifier:@"cell_topic2"];
    [self.tableView registerClass:[NoImageTableViewCell class] forCellReuseIdentifier:@"cell_noimage"];
    
    self.count = 1;
    //通知刷新UI
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishData) name:@"finishNews" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLocal) name:@"finishLocal" object:nil];
    
//    [self.navigationController.navigationBar setTintColor:[UIColor redColor]];
    //右侧重新定位
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"dingwei"] style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItemAction:)];

}





-(void)makedata
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        NSString * str = @"http://m2.qiushibaike.com/article/list/suggest?count=30&page=1&readarticles=%5B114035171%2C114030714%2C114029510%5D&AdID=1448873525721566B7382E";
        AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
        [manager GET:str parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            NSArray * array = [responseObject valueForKey:@"items"];
            for (NSDictionary * dic in array) {
                DataModel * model = [DataModel new];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error");
        }];
    });

}

#pragma Mark --- 刷新

-(void)headerRefreshing
{
    [[SoundHelper shareSound] playSound];
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [weakSelf.dataArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.header endRefreshing];
    });
    
}

-(void)footerRefreshing
{
    count += 1;
    __weak typeof  (self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * str = [NSString stringWithFormat:@"http://m2.qiushibaike.com/article/list/suggest?count=30&page=%d&readarticles=%%5B114035171%%2C114030714%%2C114029510%%5D&AdID=1448873525721566B7382E",count];
        [self loadNextData:str];
        [weakSelf.tableView.footer endRefreshing];
    });
    
    [self.tableView reloadData];
}

//下拉的时候制作数据
-(void)loadNextData:(NSString *)urlString
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL * url = [NSURL URLWithString:urlString];
        NSURLSession * session = [NSURLSession sharedSession];
        NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data != nil) {
             
                NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
                NSArray * array = dict[@"items"];
                for (NSDictionary * dic in array) {
                    DataModel * model = [[DataModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.dataArray addObject:model];
                }
                
                
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }];
        [task resume];
});
}




-(void)AboutDrawer
{
    UIBarButtonItem * left = [[UIBarButtonItem alloc]initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:self action:@selector(OpeDrawer:)];
    [left setTintColor:[UIColor colorWithRed:0.6 green:0.3 blue:0.1 alpha:1]];
    [left setImage:[UIImage imageNamed:@"side_icon@2x"]];
    self.navigationItem.leftBarButtonItem = left;
    
}

#pragma mark 抽屉效果
-(void)OpeDrawer:(UIBarButtonItem *)sender
{
    AppDelegate * temp = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (temp.leftSlider.closed) {
        [temp.leftSlider openLeftView];
    } else {
        [temp.leftSlider closeLeftView];
    }
}


#pragma mark==========TableView代理内容
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.ButtonIndex == 0) {
      return self.dataArray.count;
    } else {
      return [[LocalHelpers defaultHelpers] modelCount];
    }
    
}

//头像怎么设置
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//http://pic.qiushibaike.com/system/avtnew/3021/30214643/medium/20151030075040.jpg
    //htp://pic.qiushibaike.com/system/avtnew/1726/17260331/medium/20141007233309.jpg
#warning 在这里根据内容不同，初始化不同的cell
    if (self.ButtonIndex == 1) {
        
        News * news = [[LocalHelpers defaultHelpers] modelWithIndex:indexPath.row];
        if ([news.type isEqualToString:@"doc"]) {
            if (news.thumbnail.length == 0) {
                NoImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_noimage" forIndexPath:indexPath];
                cell.timeLable.text = news.updateTime;
                cell.titleLable.text = news.title;
                cell.commentLable.text = news.commentsall;
                return cell;
            }else{
                
                NewsOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_one" forIndexPath:indexPath];
                cell.timeLable.text = news.updateTime;
                cell.titleLable.text = news.title;
                cell.commentLable.text = news.commentsall;
                [cell.image sd_setImageWithURL:[NSURL URLWithString:news.thumbnail]];
                return cell;
            }
        }else if ([news.type isEqualToString:@"slide"]){
            NewsTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_two" forIndexPath:indexPath];
            cell.timeLable.text = news.updateTime;
            cell.titleLable.text = news.title;
            cell.commentLable.text = news.commentsall;
            NSArray * array = news.style[@"images"];
            //NSLog(@"%@", array);
            [cell.image1 sd_setImageWithURL:[NSURL URLWithString:array[0]]];
            [cell.image2 sd_setImageWithURL:[NSURL URLWithString:array[1]]];
            [cell.image3 sd_setImageWithURL:[NSURL URLWithString:array[2]]];
            return cell;
        }else if ([news.type isEqualToString:@"topic2"]){
            Topic2TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_topic2" forIndexPath:indexPath];
            cell.titleLable.text = news.title;
            cell.commentLable.text = news.commentsall;
            [cell.image sd_setImageWithURL:[NSURL URLWithString:news.thumbnail]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            return cell;
        }

        
        
        
        
        
    } else {
     
        TypePlainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
        
        
        DataModel * model = self.dataArray[indexPath.row];
        cell.contentLabel.text = model.content;
        cell.naneLabel.text = model.login;
        NSString * strstring = [NSString stringWithFormat:@"%@",model.id];
        NSString * str = [strstring substringToIndex:4];
        NSString * url = [NSString stringWithFormat:@"http://pic.qiushibaike.com/system/avtnew/%@/%@/medium/%@",str,model.id,model.icon];
        [cell.headView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"dog"]];
        
        
        [cell.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.ButtonIndex == 0) {
        self.indexPath = indexPath;
    } else {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        LocalDetailViewController * detailVC = [[LocalDetailViewController alloc] init];
        detailVC.index = indexPath.row;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}






-(void)shareButtonAction:(UIButton *)sender
{
    TypePlainTableViewCell * cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
    
    NSString * str = cell.contentLabel.text;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:str
                                     shareImage:nil
                                shareToSnsNames:nil
                                       delegate:self];
}




-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    PickButton * six = [PickButton new];
    return six;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.ButtonIndex == 0) {
        DataModel * model = self.dataArray[indexPath.row];
    NSString * str = model.content;
    CGRect r = [str boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width - 20, 20000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18.0f]} context:nil];
    
    return r.size.height + 100;

    } else {
#pragma mark --- 第二页面才走
        if (self.ButtonIndex == 1) {
            News * news = [[LocalHelpers defaultHelpers] modelWithIndex:indexPath.row];
            if ([news.type isEqualToString:@"doc"] || [news.type isEqualToString:@"topic2"]) {
                
                if (news.thumbnail.length == 0) {
                    return 65;
                }else{
                    return 80;
                }
            }else if([news.type isEqualToString:@"slide"]){
                return 120;
            }else {
                return 80;
            }
            
        }
    }
    return 120;
}


#pragma mark ---- 第二个页面

//重新选择位置
-(void)rightBarButtonItemAction:(UIBarButtonItem *)sender
{
    LocalController * localVC = [[LocalController alloc]initWithStyle:(UITableViewStyleGrouped)];
    localVC.localCity = self.city;
    localVC.nowCity = self.navigationItem.title;
    localVC.delegate = self;
    UINavigationController * localNC = [[UINavigationController alloc]initWithRootViewController:localVC];
    [self presentViewController:localNC animated:YES completion:nil];
}

-(void)finishData
{
    if (self.choicename == nil) {
        self.navigationItem.title = self.city;
    } else {
        self.navigationItem.title = self.choicename;
    }
    [self.tableView reloadData];
}
-(void)finishLocal
{
    [[LocalHelpers defaultHelpers] removeAll];
    if (self.city != nil || self.province != nil) {
        NSMutableString * str1 = [self.classify.api mutableCopy];
        NSString * str2 = [NSString stringWithFormat:@"?province=%@&city=%@&district=%@", self.province, self.city, self.district];
        [str1 appendString:str2];
        
        [LocalHelpers defaultHelpers].urlStr = str1;
        [[LocalHelpers defaultHelpers] reloadData];
    }
    [self.manager stopUpdatingLocation];
}

#pragma mark --- 城市选择的代理方法
-(void)passValue:(LocalLIst *)local
{
    self.choicetype = local.type;
    self.choicename = local.name;
    [[LocalHelpers defaultHelpers] removeAll];
    //    NSMutableString * str1 = [self.classify.api mutableCopy];
    NSMutableString * str1 = @"http://api.irecommend.ifeng.com/local.php".mutableCopy;
    NSString * str2 = [NSString stringWithFormat:@"?&choicetype=%@&choicename=%@", self.choicetype, self.choicename];
    [str1 appendString:str2];
    
    [LocalHelpers defaultHelpers].urlStr = str1;
    //    [LocalHelpers defaultHelpers].urlStr = @"http://api.irecommend.ifeng.com/local.php?&choicetype=city&choicename=包头";
    [[LocalHelpers defaultHelpers] reloadData];
}

-(void)loadData
{
    [LocalHelpers defaultHelpers].urlStr = @"http://api.irecommend.ifeng.com/local.php?&choicetype=city&choicename=北京";
    [[LocalHelpers defaultHelpers] reloadData];
    
}


#pragma mark --- 定位代理的方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation * location = locations.firstObject;
    [self.georoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * placeMark = placemarks.firstObject;
        self.province = placeMark.administrativeArea;
        self.city = placeMark.locality;
        self.district = placeMark.subLocality;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"finishLocal" object:nil];
        });
        
    }];
}




//懒加载
- (CLLocationManager *)manager
{
    if (_manager == nil) {
        self.manager = [[CLLocationManager alloc] init];
    }
    return _manager;
}

- (CLGeocoder *)georoder
{
    if (_georoder == nil) {
        self.georoder = [[CLGeocoder alloc] init];
    }
    return _georoder;
}

-(Modefy *)classify
{
    if (_classify == nil) {
        self.classify = [[Modefy alloc]init];
    }
    return _classify;
}






//#warning 自适应高度
//-(CGFloat)fitHight:(NSString *)str
//{
//
//}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
